<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of ftpManipulation
 *
 * @author hodek
 */
class FTPService {

    private $conn_id;

    public function uploadFile($contents,$remoteFile,$oldFile = null) {
        $tmp = tmpfile();
        fwrite($tmp, $contents);
        rewind($tmp);        
        $response = null;
        if (ftp_alloc($this->conn_id, strlen($contents)*16, $result)) {
            //echo "Space successfully allocated on server.  Sending $contents.\n";            
            if ($oldFile != null){
                $response = ftp_delete($this->conn_id, $oldFile);
                //echo "\n\nResponse delete: ".$response;
            }
            $response = ftp_fput($this->conn_id, $remoteFile, $tmp, FTP_BINARY);    
            //echo "\n\nResponse fput: ".$response;
        } else {
            echo "Unable to allocate space on server.  Server said: $result\n";
        }
        fclose($tmp);
        return $response;
    }

    public function setConnID($id) {
        $this->conn_id = $id;
    }

    public function closeFTP() {
        ftp_close($this->conn_id);
    }

}

/**
 *
 * @param type $server
 * @param type $userName
 * @param type $pass
 * @param type $dir
 * @return FTPService 
 */
function connectFTP($server, $userName, $pass, $dir) {
    $conn_id = ftp_connect($server);
    $login_result = ftp_login($conn_id, $userName, $pass);
    ftp_pasv($conn_id, true);
    if ((!$conn_id) || (!$login_result)) {
        echo "FTP connection has failed!";
        echo "Attempted to connect to $ftp_server for user $ftp_user_name";
        exit;
    } else {
//        echo "Connected to $ftp_server, for user $ftp_user_name";
        ftp_chdir($conn_id, $dir);        
    }
    $ftp = new FTPService();
    $ftp->setConnID($conn_id);
    return $ftp;
}

?>
